from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect

class AuthMiddleware(MiddlewareMixin):

    # 如果未经验证，则重定向用户到登录页面
    def process_request(self, request):
        path = request.path_info
        if ((path == '/auth/login/' or path == '/auth/register/'or
                path == '/auth/refresh_captcha/' or path.startswith('/captcha/'))
                or path == '/auth/send_email_captch/'):
            return None
        elif not request.session.get('user_email'):
            return redirect('authApp:login')
        else:
            return None

    def process_view(self, request, callback, callback_args, callback_kwargs):
        return None

    # 如果用户正在尝试访问登录页面或注册页面，则不执行任何操作，允许用户继续访问。
    def process_response(self, request, response):
        return response